package net.esj.basic.core.view.interceptor;

import java.util.Enumeration;

import net.esj.basic.core.view.action.SearcherActionAware;
import net.esj.basic.core.view.tools.ActionContext;
import net.esj.basic.utils.Validators;
import net.esj.basic.utils.view.JavaTypeFormater;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 通用表达式 _searcher_字段_biaodashi
 * @author Administrator
 *
 */
public class SearcherInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Object action = invocation.getAction(); 
		try{
			if(action instanceof SearcherActionAware){
				SearcherActionAware aware = (SearcherActionAware) action;
				Enumeration enumeration = ActionContext.getRequest().getParameterNames();
				while (enumeration.hasMoreElements()) {
					String name = (String) enumeration.nextElement();
					String value = ActionContext.getRequest().getParameter(name).trim();
					if(Validators.isEmpty(value)){
						continue;
					}
					if (name.startsWith(SearcherActionAware.SEARCH_PREFIX)) {
						name = name.substring(SearcherActionAware.SEARCH_PREFIX.length());
						Object v = parseValue(value, name);
						String[] opAndqn = parseOperatorAndQueryname(name);
						ActionContext.addSearchColumn(aware.getSearcherName(),opAndqn[1],opAndqn[0],value,v);
					}else if(name.startsWith(SearcherActionAware.ORDER_BY_PREFIX)){
						if(aware.singleOrder()){
							ActionContext.clearSearchOrder(aware.getSearcherName());
						}
						name = name.substring(SearcherActionAware.ORDER_BY_PREFIX.length());
						ActionContext.addSearchOrder(aware.getSearcherName(), name, value, value);
					}
				}
			}
			return invocation.invoke();
		}finally{
			if(action instanceof SearcherActionAware){
				if(((SearcherActionAware)action).clearOnReload()){
					ActionContext.clearSearcher(((SearcherActionAware)action).getSearcherName());
				}
			}
		}
		
	}

	private static Object parseValue(String value,String key){
		if(key.indexOf("?")>0){
			String k = key.substring(key.indexOf("?")+1);
			return JavaTypeFormater.formate(k, value);
		}else{
			return value;
		}
	}
	
	private static String[] parseOperatorAndQueryname(String name){
		String[] value = new String[2];
		if(name.indexOf("?")>0){
			name = name.substring(0, name.indexOf("?"));
		}
		if(name.indexOf("_")>0){
			value[0] = name.substring(0,name.indexOf("_"));
			value[1]  = name.substring(name.indexOf("_")+1).replaceAll("#", "\\.");//将#转为.
		}else{
			value[1]  = name.replaceAll("#", "\\.");
		}
		return value;
	}
	
}
